package com.crm.common.utils;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {

    /**
     * 获取客户端IP地址
     *
     * @param request HttpServletRequest
     * @return 客户端IP
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }

        // 通过HTTP头中的常见字段尝试获取真实IP
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 如果使用了代理服务器，X-Forwarded-For会包含多个IP，第一个为客户端真实IP
        if ("X-Forwarded-For".equalsIgnoreCase(ip) && ip.indexOf(",") > 0) {
            ip = ip.split(",")[0].trim();
        }

        // 处理本地回环地址和IPv6地址
        if ("127.0.0.1".equals(ip) || "localhost".equals(ip)) {
            ip = "127.0.0.1";
        }

        return ip;
    }

    /**
     * 判断是否是内网IP
     *
     * @param ip IP地址
     * @return 是否为内网IP
     */
    public static boolean isInternalIp(String ip) {
        if (ip == null || ip.isEmpty()) {
            return true; // 默认认为是内网
        }
        return ip.startsWith("192.168.") || ip.startsWith("10.") || ip.startsWith("172.16.")
                || ip.startsWith("172.17.") || ip.startsWith("172.18.") || ip.startsWith("172.19.")
                || ip.startsWith("172.20.") || ip.startsWith("172.21.") || ip.startsWith("172.22.")
                || ip.startsWith("172.23.") || ip.startsWith("172.24.") || ip.startsWith("172.25.")
                || ip.startsWith("172.26.") || ip.startsWith("172.27.") || ip.startsWith("172.28.")
                || ip.startsWith("172.29.") || ip.startsWith("172.30.") || ip.startsWith("172.31.");
    }
}
